package beautiful.butterfly.distributed_service_container.application;


import ch.qos.logback.access.joran.JoranConfigurator;
import ch.qos.logback.classic.LoggerContext;
import com.google.common.base.Preconditions;
import org.slf4j.impl.StaticLoggerBinder;

import java.io.File;
import java.io.PrintWriter;

public class BootStrap
{
    public static ClassLoader classLoader = null;

    public static ClassLoader getClassLoader()
    {
        return BootStrap.classLoader;
    }

    public static void setClassLoader(ClassLoader classLoader)
    {
        Preconditions.checkNotNull(classLoader, "classLoader is null");
        if (BootStrap.classLoader != null)
        {
            throw new IllegalArgumentException("classLoader is not null");
        }
        BootStrap.classLoader = classLoader;
    }

    public static void main(String[] as) throws Exception
    {
        bootStrap(BootStrap.class);
    }

    /**
     * 对外提供服务的入口
     */
    public static void bootStrap(Class clazz) throws Exception
    {
        try
        {
            String path = Paths.getClassPath(clazz);//class path跟路径(资源路径的父级路径,非class路径)
            System.out.println("当前系统classpath根路径:" + path);
            BootStrap.setClassLoader(Thread.currentThread().getContextClassLoader());
            //
            File logFile = new File(path + File.separator + "logback.xml");
            if (!logFile.exists())
            {
                System.err.println("读取logback配置文件失败:" + logFile.getAbsolutePath());
            } else
            {
                LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton()
                        .getLoggerFactory();
                loggerContext.reset();
                JoranConfigurator configurator = new JoranConfigurator();
                configurator.setContext(loggerContext);
                configurator.doConfigure(logFile.getAbsoluteFile());
            }
            //
            Application application = new Application(path);//统一在这里计算路径与框架里面的信息无关
            application.start();
        } catch (Exception e)
        {
            PrintWriter printWriter = new PrintWriter(System.out);
            e.printStackTrace(printWriter);
            printWriter.flush();
            printWriter.close();
            System.out.println("错误信息:" + printWriter.toString());
        }
    }
}
